﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BezierRay : MonoBehaviour {
    //(1-t)
    public float length;
    [Range(1,180)]
    public float maxAngle;
    [Range(5,20)]
    public int tracerDensity = 10;
    public LineRenderer line;
	// Use this for initialization
	void Start () {
        line.positionCount = tracerDensity;
	}
	
	// Update is called once per frame
	void Update () {
        for (int i = 0; i < tracerDensity; i++)
        {
            line.SetPosition(i, GetBeizierPos((float)i / (tracerDensity - 1)));
        }
	}

    Vector3 GetBeizierPos(float t)
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position,transform.forward,out hit))
        {
            
        }
        Vector3 p0 = transform.position;
        Vector3 p1 = transform.position + transform.forward * length;
        Debug.DrawLine(p0, p1, Color.red);
        Vector3 f = transform.forward;
        f.y = 0;
        Vector3 p2 = p0 + f.normalized * Vector3.Distance(new Vector3(p0.x, 0, p0.z), new Vector3(p1.x, 0, p1.z)) * 2;
        Vector3 dir2 = p2 - p1;

        if (Vector3.Angle(-transform.forward,dir2) > maxAngle)
        {
            Quaternion q = Quaternion.AngleAxis(maxAngle, transform.transform.right);
            dir2 = q * -transform.forward;
        }
        RaycastHit hit2;
        if (Physics.Raycast(p1, dir2, out hit2, 100))
        {
            p2 = hit2.point;
        }
        Debug.DrawLine(p1, p2, Color.green);
        Vector3 p = (1 - t) * (1 - t) * p0 + 2 * t * (1 - t) * p1 + t * t * p2;
        return p;
    }
}
